/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.inven.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.apache.commons.collections.map.LinkedMap;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import ssn.common.code.service.CodeService;
import ssn.common.code.vo.CodeVO;
import ssn.common.util.DateUtil;
import ssn.common.util.Util;
import ssn.common.view.CommonExcelView;
import ssn.common.vo.SearchVO;
import ssn.common.vo.WaterConstants;
import ssn.common.web.CommonController;
import ssn.inven.service.InvenService;
import egovframework.rte.fdl.string.EgovDateUtil;
import egovframework.rte.fdl.string.EgovStringUtil;


/**  
 * @Class Name : 
 * @Description : 
 * @Modification Logrmation  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2009.03.16           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@SuppressWarnings({"rawtypes","unchecked"})
@Controller
public class InvenController extends CommonController{
	
    @Resource(name = "invenService")
    private InvenService invenService;

    @Resource(name = "codeService")
    private CodeService codeService;
    
    
    /**
	 * 약품 사용 현황
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/inven/useDrug.do")
    public String useDrug(@ModelAttribute("searchVO") SearchVO searchVO, ModelMap model) throws Exception {
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = invenService.selectInvenOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    	}else{
    		searchVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    	}
    	
    	if(EgovStringUtil.isEmpty(searchVO.getSearchEdate())){
    		searchVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(searchVO.getSearchSdate())){
    		searchVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(searchVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	Map resultMap = invenService.selectDailyUseDrug(searchVO);
    	List codeList = (List)resultMap.get("invenCodeList");
    	List resultList = (List)resultMap.get("resultList");
    	List resultSumList = (List)resultMap.get("resultSumList");
    	model.addAttribute("searchVO", searchVO);
    	model.addAttribute("codeList", codeList);
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("resultSumList", resultSumList);
        return "/inven/useDrug";
    }
    
    /**
     * 약품 사용 현황 엑셀 다운로드
     * @param 
     * @param model
     * @return 
     * @exception Exception
     */
    @RequestMapping(value="/inven/useDrugExcelDown.do")
    public ModelAndView useDrugExcelDown(@ModelAttribute("searchVO") SearchVO searchVO, ModelMap model) throws Exception {
    	ModelAndView mav = new ModelAndView(new CommonExcelView());
    	String sheetName = "";
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = invenService.selectInvenOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    		sheetName = Util.getServiceAreaName((List)resultOtherInfo.get("serviceareaList"), searchVO.getSearchServiceArea());
    	}else{
    		searchVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    		sheetName = loginSessionInfo.get().getSsa_area_name();
    	}
    	
    	if(EgovStringUtil.isEmpty(searchVO.getSearchEdate())){
    		searchVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(searchVO.getSearchSdate())){
    		searchVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(searchVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	
    	Map resultMap = invenService.selectDailyUseDrug(searchVO);
    	List codeList = (List)resultMap.get("invenCodeList");
    	List resultList = (List)resultMap.get("resultList");
    	List resultSumList = (List)resultMap.get("resultSumList");
    	
    	Map resultExcelMap = new HashMap();
    	Map headerName = new LinkedMap();
    	
    	/**
    	 * 약품 사용 현황 컬럼 네임이 코드키이기 때문에 코드 리스트로 header 를 생성
    	 */
    	headerName.put("dailyDate", "날짜");
    	for(int i=0; i<codeList.size();i++){
    		CodeVO tempCodeVO = (CodeVO)codeList.get(i);
    		headerName.put(tempCodeVO.getScc_code_key(), tempCodeVO.getScc_code_name());
    	}
    	
    	/**
    	 * 엑셀에서 통계 부분까지 한번에 나오게 하기위해 리스트를 합침, 꽁수로 사용량, 입고량, 이월량, 재고량 텍스트부분에 alias 로 dailyDate 를 줌.
    	 */
    	resultList.addAll(resultSumList);
    	
    	resultExcelMap.put("sheetName", sheetName);
    	resultExcelMap.put("fileName", sheetName+"-약품사용현황-"+searchVO.getSearchSdate()+"~"+searchVO.getSearchEdate()+".xls");
    	resultExcelMap.put("headerName", headerName);
    	resultExcelMap.put("excelList", resultList);
    	mav.addObject("excelMap", resultExcelMap);
    	
    	return mav;
    }
    
    
    /**
     * 약품관리
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/inven/useDrugManage.do")
    public String useDrugManage(ModelMap model) throws Exception {
    	model.addAttribute("resultList", codeService.selectCodeInfoListOrderBy("INVEN"));
    	return "/inven/useDrugManage";
    }
    
    /**
     * 약품관리 저장
     * @param codeVO
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/inven/invenSave.do", method=RequestMethod.POST)
    public String manageUseDrug(@ModelAttribute("codeVO")@Valid CodeVO codeVO, BindingResult bindingResult) throws Exception{
    	
    
    	String invenRefKey = propertiesService.getString("scc.codekey.inven");
		List<CodeVO> tempInsertCodeVO = new ArrayList<CodeVO>();
		List<CodeVO> tempUpdateCodeVO = new ArrayList<CodeVO>();

		boolean codeChkInsert = false;
		boolean codeChkUpdate = false;
		int count = 0;
		
		for(CodeVO tempIV : codeVO.getCodeVoList()){
			if(EgovStringUtil.isEmpty(tempIV.getScc_code_key())){
				CodeVO tempVO = new CodeVO();
				String codeKey = invenRefKey+EgovDateUtil.getCurrentDateTimeAsString()+count;
				tempVO.setScc_code_key(codeKey);
				tempVO.setScc_code_name(tempIV.getScc_code_name());
				tempVO.setScc_flag_yn("Y");
				tempVO.setScc_ref_key(invenRefKey);
				tempIV.setScc_code_key(codeKey);
				tempInsertCodeVO.add(tempVO);
				codeChkInsert = true;
				count++;
			}else{
				CodeVO tempVO = new CodeVO();
				tempVO.setScc_code_key(tempIV.getScc_code_key());
				tempVO.setScc_code_name(tempIV.getScc_code_name());
				tempVO.setScc_flag_yn(tempIV.getScc_flag_yn());
				tempUpdateCodeVO.add(tempVO);
				codeChkUpdate = true;
			}
		}
		
		if(codeChkInsert)
			codeService.insertCodeInfo(tempInsertCodeVO);
		
		if(codeChkUpdate)
			codeService.updateCodeInfo(tempUpdateCodeVO);
		
    	return "redirect:/inven/useDrugManage.do";
    }
    
}
